package models

import (
	"errors"
	"fmt"
	//	"qysoft/libs"
	"reflect"
	"strings"
	"time"

	"github.com/astaxie/beego"

	"github.com/astaxie/beego/orm"
)

type Livechannel struct {
	Id           string        `orm:"column(id);pk"`
	OrgName      string        `orm:"column(org_name);null"`
	Stream       string        `orm:"column(stream)"`
	Vhost        string        `orm:"column(vhost)"`
	Type         int           `orm:"column(type);null"`
	Img          string        `orm:"column(img);null"`
	Scope        int           `orm:"column(scope);null"`
	Title        string        `orm:"column(title);null"`
	Url          string        `orm:"column(url);null"`
	Clicks       int           `orm:"column(clicks);null"`
	Lng          float64       `orm:"column(lng);null"`
	Lat          float64       `orm:"column(lat);null"`
	Address      string        `orm:"column(address);null"`
	Status       int           `orm:"column(status)"`
	Remark       string        `orm:"column(remark);null"`
	Isdelete     int           `orm:"column(isdelete);default(0)"`
	Ctime        time.Time     `orm:"column(ctime);type(timestamp with time zone)"`
	Creater      string        `orm:"column(creater)"`
	Utime        time.Time     `orm:"column(utime);type(timestamp with time zone)"`
	Updater      string        `orm:"column(updater)"`
	User         []*User       `orm:"reverse(many)"`
	Organization *Organization `orm:"rel(fk)"`
	Dept         *Dept         `orm:"rel(fk)"`
}

func (t *Livechannel) TableName() string {
	return "vid_live"
}

func init() {
	orm.RegisterModel(new(Livechannel))
}

// AddLivechannel insert a new Livechannel into database and returns
// last inserted Id on success.
func AddLivechannel(m *Livechannel) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

// GetLivechannelById retrieves Livechannel by Id. Returns error if
// Id doesn't exist
func GetLivechannelById(id string) (v *Livechannel, err error) {
	o := orm.NewOrm()
	v = &Livechannel{Id: id}
	if err = o.Read(v); err == nil {
		o.LoadRelated(v, "User")
		beego.Debug(v.User, v.Title)
		return v, nil
	}
	return nil, err
}

// GetAllLivechannel retrieves all Livechannel matches certain condition. Returns empty list if
// no records exist
func GetAllLivechannel(query map[string]interface{}, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []interface{}, count int64, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Livechannel))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, 0, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, 0, errors.New("Error: unused 'order' fields")
		}
	}

	var l []orm.Params
	count, err = qs.Count()
	qs = qs.RelatedSel().OrderBy(sortFields...)
	if _, err = qs.Limit(limit, offset).Values(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				if v["Scope"].(int64) == 0 {
					v["Sname"] = "本部门"
				} else if v["Scope"].(int64) == 1 {
					v["Sname"] = "全单位"
				} else if v["Scope"].(int64) == 2 {
					v["Sname"] = "全系统"
				} else if v["Scope"].(int64) == 3 {
					v["Sname"] = "指定用户"
				}
				ml = append(ml, v)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, count, nil
	}
	return nil, 0, err
}

// UpdateLivechannel updates Livechannel by Id and returns error if
// the record to be updated doesn't exist
func UpdateLivechannelById(m *Livechannel) (err error) {
	o := orm.NewOrm()
	v := Livechannel{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeleteLivechannel deletes Livechannel by Id and returns error if
// the record to be deleted doesn't exist
func DeleteLivechannel(id string) (err error) {
	o := orm.NewOrm()
	v := Livechannel{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&Livechannel{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

// 软删除直播频道 Id and returns error if
// the record to be deleted doesn't exist
func SoftDeleteLivechannel(id, uname string) (err error) {
	o := orm.NewOrm()
	v := Livechannel{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		v.Isdelete = 1
		v.Updater = uname
		v.Utime = time.Now()
		_, err = o.Update(&v)
	}
	return
}

// 根据直播编号获取频道信息
func GetLivechannelByStream(stream string) (*Livechannel, error) {
	o := orm.NewOrm()
	var live Livechannel

	channel := new(Livechannel)
	qs := o.QueryTable(channel)
	qs = qs.Filter("Stream", stream).Filter("Isdelete", 0).Filter("Status", 1).RelatedSel().Limit(1)
	err := qs.One(&live)

	//	o := orm.NewOrm()
	//	v = &Livechannel{Stream: stream}
	//	if err = o.Read(v, "Stream"); err == nil {
	//		o.LoadRelated(v, "Organization")
	//		return v, nil
	//	}
	return &live, err
}

//Desc 根据单位统计直播频道观看情况
//Param OrgId 单位id
//return 统计结果，异常
func StatisticLiveChannelByOrgId(orgId int64) ([]orm.Params, error) {
	sql := "SELECT b.id,b.title,Sum(b.clicks) AS clicks,Sum(b.looklong) AS looklong " +
		"FROM public.vid_watchhistory a RIGHT JOIN  public.vid_live b on a.vid_id = b.id AND a.type=2 AND a.org_id = ? " +
		"GROUP BY b.id,b.title " +
		"ORDER BY b.id ASC"
	var maps []orm.Params
	o := orm.NewOrm()
	_, err := o.Raw(sql, orgId).Values(&maps)
	return maps, err
}

//Desc 根据直播标识获取直播频道
//Param stream 直播频道唯一标识
//return int64,[]Livechannel,error
func GetLiveChannelListByStream(stream string) (int64, []Livechannel, error) {
	sql := "SELECT * FROM public.vid_live ta WHERE ta.stream = ? and ta.isdelete=0"
	o := orm.NewOrm()
	var ls []Livechannel
	sum, err := o.Raw(sql, stream).QueryRows(&ls)
	return sum, ls, err
}

//Desc 添加直播频道的观看次数
//Param url 直播频道播放的url
//return error
func AddLiveChannelClicks(url string) error {
	o := orm.NewOrm()
	_, err := o.QueryTable(new(Livechannel)).Filter("url", url).Update(orm.Params{"clicks": orm.ColValue(orm.ColAdd, 1)})
	return err
}

//根据orgid获取直播频道列表
func GetChannelByOrgid(oid int64, page int64, page_size int64) (channels []orm.Params, count int64, err error) {
	o := orm.NewOrm()
	channel := new(Livechannel)
	qs := o.QueryTable(channel).Filter("org_id", oid)
	qs.Limit(-1).Values(&channels)
	count, err = qs.Count()
	var offset int64
	if page <= 1 {
		offset = 0
	} else {
		offset = (page - 1) * page_size
	}
	_, err = qs.Limit(page_size, offset).Values(&channels)

	return
}

//获取所有视频列表
func GetChannelList() (ml []interface{}, count int64, err error) {
	o := orm.NewOrm()
	channel := new(Livechannel)
	qs := o.QueryTable(channel)
	qs = qs.Filter("Isdelete", 0).Filter("Status", 1).OrderBy("clicks")
	var l []Livechannel
	qs.Limit(-1).All(&l)
	rtmpserver := "rtmp://" + beego.AppConfig.String("StreadmAddress") + ":1935/"
	count, err = qs.Count()
	for k, v := range l {
		lc := make(map[string]interface{})
		lc["type"] = "rtmp/flv"
		lc["index"] = k
		lc["id"] = v.Id
		lc["name"] = v.Title
		lc["url"] = v.Url
		lc["src"] = rtmpserver + v.Url
		lc["img"] = v.Img
		ml = append(ml, lc)
	}
	return
}

//获取所有单位有效视频列表
func GetChannelListByOrg(user *User) (ml []interface{}, err error) {
	o := orm.NewOrm()
	channel := new(Livechannel)
	qs := o.QueryTable(channel) //部门全部直播频道
	qs = qs.Filter("Isdelete", 0).Filter("Status", 1).OrderBy("clicks")
	os := qs //单位全部直播频道
	ss := qs //系统全部直播频道
	us := qs //用户单独授权
	var l []Livechannel
	qs.Filter("scope", 0).Filter("Dept__Id", user.Dept[0].Id).Limit(-1).All(&l)
	rtmpserver := "rtmp://" + beego.AppConfig.String("StreadmAddress") + ":1935/"
	beego.Debug("scope 0", l)

	for k, v := range l {
		lc := make(map[string]interface{})
		lc["type"] = "rtmp/flv"
		lc["index"] = k
		lc["id"] = v.Id
		lc["name"] = v.Title
		lc["url"] = v.Url
		lc["src"] = rtmpserver + v.Url
		lc["img"] = v.Img
		ml = append(ml, lc)
	}

	//单位全部直播频道
	//	pids := new([]int64)
	//	GetParentOrg(oid, pids)
	l = l[:0]
	os.Filter("Organization__Id", user.Organization.Id).Filter("scope", 1).Limit(-1).All(&l)
	beego.Debug("scope 1", l)

	for k, v := range l {
		lc := make(map[string]interface{})
		lc["type"] = "rtmp/flv"
		lc["index"] = k
		lc["id"] = v.Id
		lc["name"] = v.Title
		lc["url"] = v.Url
		lc["src"] = rtmpserver + v.Url
		lc["img"] = v.Img
		ml = append(ml, lc)
	}

	//系统全部直播频道
	l = l[:0]
	ss.Filter("scope", 2).Limit(-1).All(&l)
	beego.Debug("scope 2", l)

	for k, v := range l {
		lc := make(map[string]interface{})
		lc["type"] = "rtmp/flv"
		lc["index"] = k
		lc["id"] = v.Id
		lc["name"] = v.Title
		lc["url"] = v.Url
		lc["src"] = rtmpserver + v.Url
		lc["img"] = v.Img
		ml = append(ml, lc)
	}

	//用户单独授权
	l = l[:0]
	ul := user.Livechannel
	if len(ul) > 0 {
		beego.Debug("scope 3", l)
		_, err = us.Filter("id__in", ul).Filter("scope", 3).Limit(-1).All(&l)
		for k, v := range l {
			lc := make(map[string]interface{})
			lc["type"] = "rtmp/flv"
			lc["index"] = k
			lc["id"] = v.Id
			lc["name"] = v.Title
			lc["url"] = v.Url
			lc["src"] = rtmpserver + v.Url
			lc["img"] = v.Img
			ml = append(ml, lc)
		}
	}
	return
}

//Desc 根据用户id获取用户直播授权直播id数组
//Param uid 用户id
//return lives []int64,error
func GetUserLiveByUser(uid int64) (lives orm.ParamsList, err error) {
	o := orm.NewOrm()
	//	var userList []UserLive
	qs := o.QueryTable("sys_user_vid_lives").Filter("UserId", uid)
	_, err = qs.Limit(-1).ValuesFlat(&lives, "sys_live_id")

	return
}

//Desc 根据直播id删除用户授权
//Param  lid 直播id
//return error
func DeleteUserLiveByLiveId(lid string) (err error) {
	o := orm.NewOrm()
	_, err = o.Raw("DELETE FROM sys_user_vid_lives WHERE vid_live_id=?", lid).Exec()
	return
}

//直播频道授权用户
func AddUserLive(uid, lid string) (int64, error) {
	o := orm.NewOrm()
	user := User{Id: uid}
	live := Livechannel{Id: lid}
	m2m := o.QueryM2M(&live, "User")
	num, err := m2m.Add(&user)
	return num, err
}
